using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Runtime.InteropServices;

using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.WowAddonStudio.Lua.LanguageService.Support;
using Microsoft.WowAddonStudio.Services;
using IServiceProvider=System.IServiceProvider;

namespace Microsoft.WowAddonStudio.Lua.LanguageService
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // A Visual Studio component can be registered under different registry roots; for instance
    // when you debug your package you want to register it in the experimental hive. This
    // attribute specifies the registry root to use if no one is provided to regpkg.exe with
    // the /root switch.
    [DefaultRegistryRoot(@"Software\Microsoft\AppEnv\9.0\Apps\WowAddonStudio")]
    // In order be loaded inside Visual Studio in a machine that has not the VS SDK installed, 
    // package needs to have a valid load key (it can be requested at 
    // http://msdn.microsoft.com/vstudio/extend/). This attributes tells the shell that this 
    // package has a load key embedded in its resources.
    [ProvideLoadKey("Standard", "1.0", "Lua Language Service", "WowAddonStudio", 100)]
    // Provide LanguageService as a Visual Studio service
    [ProvideService(typeof(ILibraryManager), ServiceName = "Library Manager")]
    [ProvideService(typeof(ILuaLanguageService), ServiceName = "Lua Language Service")]
    [ProvideService(typeof(LuaLanguageService), ServiceName = "Lua Language Service")]
    // Provide the language service for the .lua extension
    [ProvideLanguageExtension(typeof(LuaLanguageService), Configuration.Extension)]
    // Provide and configure the language service features
    [ProvideLanguageService(typeof(LuaLanguageService), "Lua", 101,
        AutoOutlining = true,
        CodeSense = true, 
        CodeSenseDelay = 500,
        DefaultToInsertSpaces = true,
        ShowSmartIndent = true,
        EnableCommenting = true,
        MatchBraces = true, 
        ShowCompletion = true, 
        ShowMatchingBrace = true, 
        EnableAsyncCompletion = true)]
    [Guid(GuidStrings.LuaLanguageServicePackage)]
    public sealed class LuaLanguageServicePackage : Package
    {
        private uint idleComponentId;

        /// <summary>
        /// Called when the VSPackage is loaded by Visual Studio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            IServiceContainer serviceContainer = this;

            // Register caall back for Library Manager
            serviceContainer.AddService(typeof(ILibraryManager), OnCreateLibraryManager, true);

            // Register callback for Language Service and its interface that returns the language service itself
            serviceContainer.AddService(typeof(LuaLanguageService), OnCreateLuaLanguageService, true);
            serviceContainer.AddService(typeof(ILuaLanguageService), OnCreateLuaLanguageService, true);
        }

        private ILibraryManager OnCreateLibraryManager(IServiceContainer container, Type serviceType)
        {
            if (serviceType == typeof(ILibraryManager))
                return new LibraryManager(this);

            return null;
        }

        private object OnCreateLuaLanguageService(IServiceContainer container, Type serviceType)
        {
            if (serviceType == typeof(LuaLanguageService))
            {
                var luaLanguageService = new LuaLanguageService();
                luaLanguageService.SetSite(this);

                InitializeIdleComponent();
                return luaLanguageService;
            }

            if (serviceType == typeof(ILuaLanguageService))
                return container.GetService(typeof(LuaLanguageService));

            return null;
        }

        private void InitializeIdleComponent()
        {
            // register for idle time callbacks
            if (idleComponentId == 0)
            {
                var crinfo = new OLECRINFO[1];
                crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime | (uint)_OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 1000;
                ComponentManager.FRegisterComponent(new IdleComponent(this), crinfo, out idleComponentId);
            }
        }

        /// <summary>
        /// Dispose resources.
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (idleComponentId != 0)
                {
                    ComponentManager.FRevokeComponent(idleComponentId);
                    idleComponentId = 0;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        /// <summary>
        /// Gets the component manager for the package.
        /// </summary>
        /// <returns>An IOleComponentManager object.</returns>
        private IOleComponentManager ComponentManager
        {
            get { return (IOleComponentManager)GetService(typeof(SOleComponentManager)); }
        }

        #region IdleComponent

        private class IdleComponent : IOleComponent
        {
            private readonly LuaLanguageServicePackage owner;

            public IdleComponent(LuaLanguageServicePackage owner)
            {
                this.owner = owner;
            }

            public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam)
            {
                return VSConstants.S_FALSE;
            }

            public int FPreTranslateMessage(MSG[] pMsg)
            {
                return VSConstants.S_OK;
            }

            public void OnEnterState(uint uStateID, int fEnter)
            {
            }

            public void OnAppActivate(int fActive, uint dwOtherThreadID)
            {
            }

            public void OnLoseActivation()
            {
            }

            public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved)
            {
            }

            public int FDoIdle(uint grfidlef)
            {
                var languageService = (ILuaLanguageService)owner.GetService(typeof(ILuaLanguageService));
                if (languageService != null)
                    languageService.OnIdle((grfidlef & (uint)_OLEIDLEF.oleidlefPeriodic) != 0);
                return VSConstants.S_OK;
            }

            public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked)
            {
                return VSConstants.S_FALSE;
            }

            public int FQueryTerminate(int fPromptUser)
            {
                return VSConstants.S_FALSE;
            }

            public void Terminate()
            {
            }

            public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved)
            {
                return IntPtr.Zero;
            }
        }

        #endregion
    }
}